package com.gaswell.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaswell.entity.Qba01;
import com.gaswell.mapper.FindLastMMapper;
import com.gaswell.mapper.RtuDataMapper;
import com.gaswell.pojo.Diagnosis;
import com.gaswell.pojo.Qj;
import com.gaswell.pojo.RtuData;
import com.gaswell.service.*;
import com.gaswell.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.Future;

@Service
@DS("rtu")
public class RtuDataServiceImpl extends ServiceImpl<RtuDataMapper, RtuData> implements RtuDataService {

    @Autowired
    private RtuDataMapper rtuDataMapper;
    @Autowired
    private IQba01Service qba01Service;

    @Autowired
    private RtuDataService2 rtuDataService2;

    @Autowired
    private DiagnosisNewService diagnosisNewService;

    @Autowired
    private QjService qjService;

    @Autowired
    RtuDataService rtuDataService;
    @Autowired
    private FindLastMMapper findLastMMapper;

    @Autowired
    private FindLastMservice findLastMservice;

    @Autowired
    DiagnosisService  diagnosisService;


    @Override
    public FindLastDataVo2 judgeDiagnosis(List<Diagnosis> dataByTime,FindLastDataVo2 findLastDataVo,Qba01 qba01) {
//      填充日数据
        if (qba01 != null) {
            DecimalFormat decimalFormat = new DecimalFormat("#0.00");
            String cjsj = findLastDataVo.getCjsj();
            String[] s = StringUtils.split(cjsj, " ");
            findLastDataVo.setRbrq(s[0]);
            BigDecimal rcql_b = null;
            BigDecimal rcsl_b = null;
            if (qba01.getRcql() != null)
                rcql_b = new BigDecimal(decimalFormat.format(qba01.getRcql()));
            if (qba01.getRcsl() != null)
                rcsl_b = new BigDecimal(decimalFormat.format(qba01.getRcsl()));
            findLastDataVo.setRcql(rcql_b);
            findLastDataVo.setRcsl(rcsl_b);
            findLastDataVo.setRq(qba01.getRq());
            findLastDataVo.setScsj(qba01.getScsj());
        }
//      判断diagnosis中的情况
        StringBuilder work = new StringBuilder();
        StringBuilder data = new StringBuilder();
        boolean dataNull = false;
        boolean distortion = false;
        boolean deviation = false;
        boolean jy = false;
        boolean dd = false;
        boolean jyfx = false;
        List<String> record = new LinkedList<>();
        List<String> record_type = new LinkedList<>();
        if(dataByTime!=null)
         for (Diagnosis diagnosis : dataByTime) {
            record.add(diagnosis.getRecord());
            record_type.add(diagnosis.getCategory());
            if (diagnosis.getCategory().equals("null")) {
                dataNull = true;
            }
            if (diagnosis.getCategory().equals("distortion")) {
                distortion = true;
            }
            if (diagnosis.getCategory().equals("deviation")) {
                deviation = true;
            }
            if (diagnosis.getCategory().equals("jy1") || diagnosis.getCategory().equals("jy2") || diagnosis.getCategory().equals("jy3")) {
                jy = true;
            }
            if (diagnosis.getCategory().equals("dd1") || diagnosis.getCategory().equals("dd2") || diagnosis.getCategory().equals("dd3") || diagnosis.getCategory().equals("dd4")) {
                dd = true;
            }
            if (diagnosis.getCategory().equals("jyfx1") || diagnosis.getCategory().equals("jyfx2")) {
                jyfx = true;
            }
        }

        findLastDataVo.setRecord(record);
        findLastDataVo.setRecord_type(record_type);
        if (jy)
            work.append("积液,");
        if (dd)
            work.append("冻堵,");
        if (jyfx)
            work.append("积液风险,");
        if (!jy && !dd && !jyfx) {
            if (dataNull || distortion || deviation)
//                        work.append("无,");
                work.append("数据异常，无法诊断,");
            else
                work.append("正常,");
        }
        if (dataNull)
            data.append("数据丢失,");
        if (distortion)
            data.append("数据失真,");
        if (deviation)
            data.append("数据趋势偏离,");
        if (!dataNull && !distortion && !deviation)
            data.append("正常,");
        work.deleteCharAt(work.toString().length() - 1);
        data.deleteCharAt(data.toString().length() - 1);
        findLastDataVo.setSjzt(data.toString());
        findLastDataVo.setGkzt(work.toString());
        return findLastDataVo;
    }

    @Override
    public Result selectByOptions(RtuData rtuData, int department) {
        LambdaQueryWrapper<RtuData> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(rtuData.getJh() != null, RtuData::getJh, rtuData.getJh());
        String date = rtuData.getCjsj();

        if (StringUtils.isNotBlank(date)) {
            String[] dates = date.split(",");
            String down = dates[0];
            String up = dates[1];
            lambdaQueryWrapper.ge(RtuData::getCjsj, down);
            lambdaQueryWrapper.le(RtuData::getCjsj, up);
        }
        if (department == 2) {
            List<String> lists = qjService.findJhByYm("川渝");
            lambdaQueryWrapper.in(RtuData::getJh, lists);
        }
        if (department == 3) {
            List<String> lists = qjService.findJhByYm("大庆");
            lambdaQueryWrapper.in(RtuData::getJh, lists);
        }
        lambdaQueryWrapper.eq(rtuData.getYGYL() != 0, RtuData::getYGYL, rtuData.getYGYL());
        lambdaQueryWrapper.eq(rtuData.getTGYL() != 0, RtuData::getTGYL, rtuData.getTGYL());
        lambdaQueryWrapper.eq(rtuData.getZQYL() != 0, RtuData::getZQYL, rtuData.getZQYL());
        lambdaQueryWrapper.eq(rtuData.getYGWD() != 0, RtuData::getYGWD, rtuData.getYGWD());
        lambdaQueryWrapper.eq(rtuData.getWSWD() != 0, RtuData::getWSWD, rtuData.getWSWD());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(rtuData.getFCS()), RtuData::getFCS, rtuData.getFCS());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(rtuData.getFOS()), RtuData::getFOS, rtuData.getFOS());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(rtuData.getVVC()), RtuData::getVVC, rtuData.getVVC());
        lambdaQueryWrapper.eq(rtuData.getSJHYL() != 0, RtuData::getSJHYL, rtuData.getSJHYL());
        lambdaQueryWrapper.eq(rtuData.getJZYL() != 0, RtuData::getJZYL, rtuData.getJZYL());
        lambdaQueryWrapper.eq(rtuData.getJRHWD() != 0, RtuData::getJRHWD, rtuData.getJRHWD());
        lambdaQueryWrapper.eq(rtuData.getSJHWD() != 0, RtuData::getSJHWD, rtuData.getSJHWD());
        lambdaQueryWrapper.eq(rtuData.getJZWD() != 0, RtuData::getJZWD, rtuData.getJZWD());
//        IPage<RtuData> iPage=new Page<>(current,size);
//        rtuDataMapper.selectPage(iPage,lambdaQueryWrapper);
        List<RtuData> list = rtuDataMapper.selectList(lambdaQueryWrapper);
        return Result.success(list);

//        return new Result(true,200,"success",iPage.getRecords(),(int)iPage.getTotal(),(int)iPage.getPages());
    }

    @Override
    public Result selectAll(int department) {
        List<RtuData> list = new ArrayList<>();
        LambdaQueryWrapper<RtuData> queryWrapper = new LambdaQueryWrapper<>();
        if (department == 1)
            list = rtuDataMapper.selectList(null);
        else if (department == 2) {
            List<String> lists = qjService.findJhByYm("川渝");
            queryWrapper.in(RtuData::getJh, lists);
            list = rtuDataMapper.selectList(queryWrapper);
        } else {
            List<String> lists = qjService.findJhByYm("大庆");
            queryWrapper.in(RtuData::getJh, lists);
            list = rtuDataMapper.selectList(queryWrapper);
        }
        return Result.success(list);
    }

    @Override
    public Result insertBatch(List<RtuData> list) {
        rtuDataMapper.insertBatchSomeColumn(list);
        return Result.success(null);
    }

    @Override
    public Result selectCount() {
        int count = rtuDataMapper.selectCount(null);
        return Result.success(count);
    }



    @Override
    public Result selectData(String ywbh, String date, String properties) {
        String[] dates = date.split(",");
        String down = dates[0];
        String up = dates[1];
        if (properties.equals("ytyc")) {
            properties = "(jkyy-jkty)";
            return Result.success(rtuDataMapper.selectDataYtyc(down, up, properties, ywbh));
        }
        return Result.success(rtuDataMapper.selectData(down, up, properties, ywbh));
    }

    @Override
    public Result findLatestData(int department) {
        List<FindLastDataVo> list = new ArrayList<>();
//        List<String> jhList=rtuDataMapper.selectAllJh();
        List<String> jhList = new ArrayList<>();
//        根据身份查询气井列表
        if (department == 1)
            jhList = qjService.findAllJh();
        else if (department == 2)
            jhList = qjService.findJhByYm("川渝");
        else
            jhList = qjService.findJhByYm("大庆");
        for (String jh : jhList) {
            FindLastDataVo findLastDataVo = new FindLastDataVo();
            RtuData rtuData = rtuDataMapper.findLatestData(jh);
            if (rtuData != null) {
                BeanUtils.copyProperties(rtuData, findLastDataVo);
                String cjsj = findLastDataVo.getCjsj();
                String[] s = StringUtils.split(cjsj, " ");
                Qba01 qba01 = qba01Service.setByDate(s[0], jh);
                Qj qj = qjService.selectOne(jh);
                if (qj != null) {
                    findLastDataVo.setZyq(qj.getScq());
                    findLastDataVo.setYm(qj.getYm());
                    findLastDataVo.setZm(qj.getZm());
                }
                if (qba01 != null) {
                    findLastDataVo.setRbrq(s[0]);
                    findLastDataVo.setRcql(qba01.getRcql());
                    findLastDataVo.setRcsl(qba01.getRcsl());
                }

                List<Diagnosis> dataByTime = diagnosisNewService.findDataByTime(jh, cjsj);
                StringBuilder work = new StringBuilder();
                StringBuilder data = new StringBuilder();
                boolean dataNull = false;
                boolean distortion = false;
                boolean deviation = false;
                boolean jy = false;
                boolean dd = false;
                boolean jyfx = false;
                for (Diagnosis diagnosis : dataByTime) {
                    if (diagnosis.getCategory().equals("null")) {
                        dataNull = true;
                    }
                    if (diagnosis.getCategory().equals("distortion")) {
                        distortion = true;
                    }
                    if (diagnosis.getCategory().equals("deviation")) {
                        deviation = true;
                    }
                    if (diagnosis.getCategory().equals("jy1") || diagnosis.getCategory().equals("jy2") || diagnosis.getCategory().equals("jy3")) {
                        jy = true;
                    }
                    if (diagnosis.getCategory().equals("dd1") || diagnosis.getCategory().equals("dd2") || diagnosis.getCategory().equals("dd3") || diagnosis.getCategory().equals("dd4")) {
                        dd = true;
                    }
                    if (diagnosis.getCategory().equals("jyfx1") || diagnosis.getCategory().equals("jyfx2")) {
                        jyfx = true;
                    }
                }
                if (jy)
                    work.append("积液,");
                if (dd)
                    work.append("冻堵,");
                if (jyfx)
                    work.append("积液风险,");
                if (!jy && !dd && !jyfx) {
                    if (dataNull || distortion || deviation)
                        work.append("无,");
                    else
                        work.append("正常,");
                }

                if (dataNull)
                    data.append("数据丢失,");
                if (distortion)
                    data.append("数据失真,");
                if (deviation)
                    data.append("数据趋势偏离,");
                if (!dataNull && !distortion && !deviation)
                    data.append("正常,");

                work.deleteCharAt(work.toString().length() - 1);
                data.deleteCharAt(data.toString().length() - 1);
                findLastDataVo.setSjzt(data.toString());
                findLastDataVo.setGkzt(work.toString());
                findLastDataVo.setYy(rtuData.getYGYL());
                findLastDataVo.setTy(rtuData.getTGYL());
                findLastDataVo.setJkwd(rtuData.getYGWD());
                list.add(findLastDataVo);
            }
        }
        return Result.success(list);
    }

    @Override
    public Result findLatestData(List<String> ywbhs, List<String> zwbhs) {
        final HashMap<String, List<Diagnosis>> diagnosisHashMap = new HashMap<>();
        final HashMap<String, Qba01> qba01HashMap = new HashMap<>();
        List<FindLastDataVo2> list = new ArrayList<>();
//      根据中英文编号查询实时数据，将实时数据和井号信息绑定在一起
        List<FindLastDataVo2> latestData2 = rtuDataMapper.findLatestData2(zwbhs.size() > 0 ? zwbhs : null, ywbhs.size() > 0 ? ywbhs : null);

        List<Diagnosis> allDataByJHAndDate = diagnosisService.findAllDataByJHAndDate(latestData2);




//      按井号进行分组
        for (Diagnosis diagnosis : allDataByJHAndDate) {
            if(!diagnosisHashMap.containsKey(diagnosis.getJh()))
                diagnosisHashMap.put(diagnosis.getJh(),new ArrayList<>());
            List<Diagnosis> diagnoses = diagnosisHashMap.get(diagnosis.getJh());
            diagnoses.add(diagnosis);
            diagnosisHashMap.put(diagnosis.getJh(),diagnoses);
        }
//      滤除无数据井号
        for (int i = 0; i < ywbhs.size(); i++) {
            if(!diagnosisHashMap.containsKey(zwbhs.get(i))
                    &&!diagnosisHashMap.containsKey(ywbhs.get(i)))
            {
                ywbhs.remove(i);
                zwbhs.remove(i);
                i--;
            }
        }

        List<Qba01> qba01s = qba01Service.GetByDateLast(ywbhs, zwbhs);

//      井号绑定日数据
        for (Qba01 qba01 : qba01s) {
            if(!qba01HashMap.containsKey(qba01.getJh()))
                qba01HashMap.put(qba01.getJh(),qba01);
        }




        for (FindLastDataVo2 findLastDataVo2 : latestData2) {
            FindLastDataVo2 findLastDataVo21 = judgeDiagnosis(diagnosisHashMap.get(findLastDataVo2.getJh()), findLastDataVo2, qba01HashMap.get(findLastDataVo2.getJh()));
            list.add(findLastDataVo21);
        }





        return Result.success(list);
    }


    @Override
    public Result findLatestData5(List<String> ywbhs,  List<String> zwbhs) {
        List<Future<Boolean>> futureList = new ArrayList<>();
        List<FindLastDataVo2> list = new ArrayList<>();
//      根据中英文编号查询实时数据，将实时数据和井号信息绑定在一起
        List<FindLastDataVo2> latestData2 = rtuDataMapper.findLatestData2(zwbhs.size() > 0 ? zwbhs : null, ywbhs.size() > 0 ? ywbhs : null);



        //     多线程查询
        for (FindLastDataVo2 findLastDataVo : latestData2) {
            Future<Boolean> latestData5_2 = rtuDataService2.findLatestData5_2(findLastDataVo, list);
            futureList.add(latestData5_2);
        }
        for (Future<?> future : futureList) {
            while (true) {//CPU高速轮询：每个future都并发轮循，判断完成状态然后获取结果，这一行，是本实现方案的精髓所在。即有10个future在高速轮询，完成一个future的获取结果，就关闭一个轮询
                if (future.isDone() && !future.isCancelled()) { //获取future成功完成状态，如果想要限制每个任务的超时时间，取消本行的状态判断+future.get(1000*1, TimeUnit.MILLISECONDS)+catch超时异常使用即可。
                    break;//当前future获取结果完毕，跳出while
                } else {
                    try {
                        Thread.sleep(1);//每次轮询休息1毫秒（CPU纳秒级），避免CPU高速轮循耗空CPU
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        Collections.sort(list);
        return Result.success(list);
    }



    //    从气井视图里拿
//    把in修改掉
    @Override
    public List<RtuData> selectList(int department) {
        LambdaQueryWrapper<RtuData> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (department == 2) {
            List<String> lists = qjService.findJhByYm("川渝");
            lambdaQueryWrapper.in(RtuData::getJh, lists);
        }
        if (department == 3) {
            List<String> lists = qjService.findJhByYm("大庆");
            lambdaQueryWrapper.in(RtuData::getJh, lists);
        }
        return rtuDataMapper.selectList(lambdaQueryWrapper);
    }

    @Override
    public List<RtuData> selectListByJHAndDate(int department, String[] jhs, String start, String end) {
        LambdaQueryWrapper<RtuData> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<String> lists = new LinkedList<>();
        if (department == 2) {
            lists = qjService.findJhByYm("川渝");
        }
        if (department == 3) {
            lists = qjService.findJhByYm("大庆");

        }
        if (StringUtils.isNotBlank(end)) {
            lambdaQueryWrapper.le(RtuData::getCjsj, end + " 23:59:59");
        }
        if (StringUtils.isNotBlank(start)) {
            lambdaQueryWrapper.ge(RtuData::getCjsj, start + " 00:00:00");
        }
        if (lists != null && lists.size() > 0) {
            lambdaQueryWrapper.in(RtuData::getJh, lists);
            if (jhs != null && jhs.length > 0)
                lambdaQueryWrapper.in(RtuData::getJh, jhs);
        }
        List<RtuData> rtuDatas = rtuDataMapper.selectList(lambdaQueryWrapper);
        System.out.println(rtuDatas);
        return rtuDatas;
    }

    @Override
    public Result selectByMutiOptions(RtuDataVo rtuDataVo, String date, int sort, int department) {
        LambdaQueryWrapper<RtuData> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (department == 2) {
//            List<String> lists = qjService.findJhByYm("川渝");
            List<QjVo> qjvos = qjService.findZwbhByYm("川渝");
            List<String> zwbhs = QjVo.getZwbhs(qjvos);
            List<String> ywbhs = QjVo.getYwbhs(qjvos);
//            lambdaQueryWrapper.and(in(RtuData::getJh, lists));
            lambdaQueryWrapper.and(l -> l.in(RtuData::getJh, zwbhs).or().in(RtuData::getJh, ywbhs));
        }
        if (department == 3) {
//            List<String> lists = qjService.findJhByYm("大庆");
//            lambdaQueryWrapper.in(RtuData::getJh, lists);
//            lambdaQueryWrapper.and(in(RtuData::getJh, lists));
            List<QjVo> qjvos = qjService.findZwbhByYm("大庆");
            List<String> zwbhs = QjVo.getZwbhs(qjvos);
            List<String> ywbhs = QjVo.getYwbhs(qjvos);
            lambdaQueryWrapper.and(l -> l.in(RtuData::getJh, zwbhs).or().in(RtuData::getJh, ywbhs));

        }

        int len = rtuDataVo.getOptions().size();
        if (StringUtils.isNotBlank(date)) {
            String[] dates = date.split(",");
            String down = dates[0];
            String up = dates[1];
            lambdaQueryWrapper.ge(RtuData::getCjsj, down);
            lambdaQueryWrapper.le(RtuData::getCjsj, up);
        }
        if (sort == 0) {
            lambdaQueryWrapper.last("order by cjsj asc");
        } else
            lambdaQueryWrapper.last("order by cjsj desc");

        List<QjVo> qjvos = new LinkedList<>();
        List<String> zwbhs = null;
        List<String> ywbhs = null;
        if (len == 0) {
            return Result.success(rtuDataMapper.selectList(lambdaQueryWrapper));
        } else if (rtuDataVo.getProperty().equals("jh")) {
            qjvos = qjService.findJhByJhs(rtuDataVo.getOptions());
//            lambdaQueryWrapper.in(RtuData::getJh, rtuDataVo.getOptions());
        } else if (rtuDataVo.getProperty().equals("scq")) {
            qjvos = qjService.findbhByScq(rtuDataVo.getOptions());
//            List<String> jhs = qjService.selectJhByScq(rtuDataVo.getOptions());
//            lambdaQueryWrapper.in(RtuData::getJh, jhs);
        } else if (rtuDataVo.getProperty().equals("ym")) {
            qjvos = qjService.findbhByYm(rtuDataVo.getOptions());
//            List<String> jhs = qjService.selectJhByYm(rtuDataVo.getOptions());
//            lambdaQueryWrapper.in(RtuData::getJh, jhs);
        } else if (rtuDataVo.getProperty().equals("zm")) {
            qjvos = qjService.findbhByZm(rtuDataVo.getOptions());
//            List<String> jhs = qjService.selectJhByZm(rtuDataVo.getOptions());
//            lambdaQueryWrapper.in(RtuData::getJh, jhs);
        }
        if (qjvos.size() > 0) {
            List<String> ywbhs1 = QjVo.getYwbhs(qjvos);
            List<String> zwbhs1 = QjVo.getZwbhs(qjvos);
            lambdaQueryWrapper.and(l -> l.in(RtuData::getJh, zwbhs1).or().in(RtuData::getJh, ywbhs1));
        } else {
            return Result.success(null);
        }
        return Result.success(rtuDataMapper.selectList(lambdaQueryWrapper));
    }


    public static void test(List<String> ll) {
        ll.add("123");
    }

    public static void main(String[] args) {
        LinkedList<String> strings = new LinkedList<>();
        test(strings);
        System.out.println(strings);
    }


}
